<template>
	<view class="addjiancha">
		<headertop :title="pagetitle" str1="oridei" :back1="back1"></headertop>
		<view class="addjianchaback">

		</view>
		<view class="" :style="{'margin-top':statusBarHeight+'px','width':'100%','height':barHeight+'px'}">
		</view>
		<view class="jianchaxm">
			<view class="cardform">
				<view class="center">
					<view class="lineform">
						<view class="lefttext">
							<span style="color:#F53F3F;">*</span>
							<span>检查项目：</span>
						</view>
						<view class="rightcontent">
							<input v-model="formData['item']" type="text" placeholder="请输入检查项目" />
						</view>
					</view>
					<view class="lineform" @click="show=true">
						<view class="lefttext">
							<span style="color:#F53F3F;">*</span>
							<span>检查日期：</span>
						</view>
						<view class="rightcontent">
							<image :src="_static('/images/riliicon.png')" class="righticon" mode="">
							</image>
							<span
								style="font-size: 28rpx;color: #86909C;">{{formData['check_time']?formData['check_time']:'请选择时间'}}</span>
						</view>
					</view>
					<view class="lineform">
						<view class="lefttext">
							<span>检查医院：</span>
						</view>
						<view class="rightcontent">
							<input v-model="formData['hospital']" type="text" placeholder="请输入医院" />
						</view>
					</view>
					<view class="lineform">
						<view class="lefttext">
							<span style="color:#F53F3F;">*</span>
							<span>检查结果：</span>
						</view>
						<view class="rightcontent">
							<input v-model="formData['result']" type="text" placeholder="请输入结果" />
						</view>
					</view>
					<view class="lineform">
						<view class="" style="width: 100%;overflow: hidden;margin-top: 24rpx;">
							<view class="lefttext">
								添加图片：
							</view>
							<view class="images">
								<view class="image" v-for="(item,index) in images" :key="index">
									<image :src="item" mode=""></image>
									<image :src="_static('/images/删除.png')" @click="shanchu(images,index)"
										class="remivon" mode=""></image>
								</view>
								<image :src="_static('/images/Group 11728@2x(1).png')" class="imageadd"
									@click="uploadImage('images')" v-if="images.length!=3" mode=""></image>

							</view>
							<view class="msgtext">
								支持格式：JPG、PNG、单个文件不能超过2m
							</view>
						</view>
					</view>
					<view class="lineform" style="border: none;">
						<view class="" style="width: 100%;overflow: hidden;margin-top: 24rpx;">
							<view class="lefttext">
								备注：
							</view>
							<view class="textsform">
								<textarea placeholder="请输入内容" cursor-spacing="100" v-model="formData['remark']"
									class="text1" id="" cols="30" rows="10"></textarea>
							</view>
						</view>
					</view>
				</view>
			</view>
			<up-popup :show="show" mode="bottom">
				<view class="xuanxiang">
					<view class="tt" style="margin-left: 30rpx;color: #888;" @click="show=false">
						取消
					</view>
					<view class="tt" style="font-weight: 600;">
						请选择检查日期
					</view>
					<view class="tt" style="margin-right: 30rpx;color: #0077BE;" @click="queding">
						确认
					</view>
				</view>
				<picker-view :indicator-style="indicatorStyle" immediate-change="true" :value="valuedate"
					@change="bindChange" class="picker-view">
					<picker-view-column>
						<view class="item" v-for="(item,index) in years" :key="index">{{item}}年</view>
					</picker-view-column>
					<picker-view-column>
						<view class="item" v-for="(item,index) in months" :key="index">{{item}}月</view>
					</picker-view-column>
					<picker-view-column>
						<view class="item" v-for="(item,index) in days" :key="index">{{item}}日</view>
					</picker-view-column>
				</picker-view>
			</up-popup>
		</view>
		<view class="fixed">
			<view class="btn" @click="savebc">
				保存检查
			</view>
		</view>
	</view>
</template>

<script setup>
	import headertop from '@/components/header.vue'
	import {
		_static
	} from '@/ulm/utils/url.js'
	import {
		ref,
		reactive,
		onMounted
	} from 'vue'
	import {
		onPageScroll,
		onLoad,
		onShow,
		onReachBottom
	} from "@dcloudio/uni-app";
	import {
		$api
	} from '../../ulm';
	import {
		getToken
	} from '@/ulm/utils/auth.js'
	const statusBarHeight = ref('')
	const indicatorStyle = ref(`height: 50px;`)
	const images = ref([])
	const formData = reactive({
		item: '',
		check_time: '',
		hospital: '',
		result: '',
		images: '',
		remark: '',
		id: undefined
	})
	import {
		baseUrl
	} from '@/ulm/config';
	const check_time = ref('')
	const texts = ref('')
	const barHeight = ref('')
	const back1 = ref('')
	const active = ref(2)
	const date = new Date()
	const years = []

	const show = ref(false)
	const day = date.getDate()
	const year = date.getFullYear()
	const months = []
	const month = date.getMonth() + 1
	const days = []
	const pagetitle = ref('')
	const valuedate = ref([9999, month - 1, day - 1])
	for (let i = 1900; i <= date.getFullYear(); i++) {
		years.push(i)
	}
	for (let i = 1; i <= 12; i++) {
		months.push(i)
	}
	for (let i = 1; i <= 31; i++) {
		days.push(i)
	}
	onLoad((opt) => {
		if (opt.id) {
			pagetitle.value = '编辑检查'
			inithuoqu(opt.id)
		} else {
			pagetitle.value = '添加检查'
		}
	})
	async function inithuoqu(id) {
		const res = await $api.checkupRecordDetail({
			id
		})
		if (res.code == 1) {
			formData.id = res.data.id
			formData.item = res.data.item
			formData.check_time = res.data.check_time
			formData.hospital = res.data.hospital
			formData.result = res.data.result
			if (res.data.images) {
				images.value = res.data.images
			}
			formData['remark'] = res.data.remark
		}
	}

	function shanchu(arr, i) {
		arr.splice(i, 1)
	}

	onMounted(() => {
		statusBarHeight.value = uni.getSystemInfoSync().statusBarHeight
		const {
			top,
			height
		} = wx.getMenuButtonBoundingClientRect();
		barHeight.value = height ? height + (top - statusBarHeight.value) * 2 : 38;
	})
	onPageScroll((e) => {
		if (e.scrollTop > 100) {
			back1.value = '#81D6FF'
		} else {
			back1.value = ''
		}
	})
	async function savebc() {
		if (!formData['item'] || !formData.check_time || !formData.result) {
			uni.showToast({
				title: '必填项不能为空',
				icon: 'none'
			})
			return
		}
		formData.images = images.value.join()
		if (pagetitle.value == '编辑检查') {
			const res1 = await $api.editCheckupRecord(formData)
			if (res1.code == 1) {
				setTimeout(function() {
					uni.showToast({
						title: '保存成功',
						icon: 'none'
					})
				}, 500);
				uni.navigateBack();
			} else {
				uni.showToast({
					title: res1.msg,
					icon: 'none'
				})
			}
			return
		}
		const res = await $api.addCheckupRecord(formData)
		if (res.code == 1) {
			setTimeout(function() {
				uni.showToast({
					title: '保存成功',
					icon: 'none'
				})
			}, 500);
			uni.navigateBack();
		} else {
			uni.showToast({
				title: res.msg,
				icon: 'none'
			})
		}
	}

	function bindChange(e) {
		const val = e.detail.value
		check_time.value =
			`${years[val[0]]}-${months[val[1]]<10?'0'+months[val[1]]:months[val[1]]}-${days[val[2]]<10?'0'+days[val[2]]:days[val[2]]}`
	}

	function queding() {
		if (!check_time.value) {
			formData['check_time'] =
				`${date.getFullYear()}-${months[month-1]<10?'0'+months[month-1]:months[month-1]}-${day<10?'0'+day:day}`
		} else {
			formData['check_time'] = check_time.value
			if (convertToTimestamp(formData['check_time']) > Date.now()) {
				formData['check_time'] = ''
				uni.showToast({
					title: '请选择正确检查日期',
					icon: 'none'
				})
				return
			}
		}
		show.value = false
	}

	function convertToTimestamp(dateStr) {
		return new Date(dateStr).getTime();
	}

	function uploadImage(str) {
		uni.chooseImage({
			count: 3 - images.value.length, // 最多可选择图片数量
			sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图
			sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机
			success: (res) => {
				const validImages = res.tempFiles.filter(file => {
					return file.size <= 2 * 1024 * 1024; // 2MB = 2 * 1024 * 1024 Bytes
				});
				if (validImages.length === 0) {
					uni.showToast({
						title: `${res.tempFiles.length - validImages.length}张图片超过2MB`,
						icon: 'none'
					});
					return;
				}
				// tempFilePath 可以作为 img 标签的 src 属性显示图片
				const tempFilePaths = res.tempFilePaths
				uploadImages(tempFilePaths, str)
			},
			fail: (err) => {

			}
		})
	}

	function uploadImages(filePaths, str) {
		const uploadTasks = filePaths.map((filePath, index) => {
			return new Promise((resolve, reject) => {
				uni.uploadFile({
					url: `${baseUrl}/api/common/upload`,
					filePath: filePath,
					name: 'file',
					formData: {
						index: index // 可以添加序号标识
					},
					header: {
						token: getToken()
					},
					success: (uploadRes) => {
						resolve(JSON.parse(uploadRes.data))
					},
					fail: (err) => {
						reject(err)
					}
				})
			})
		})

		uni.showLoading({
			title: '上传中...'
		})

		Promise.all(uploadTasks)
			.then(results => {
				for (var i in results) {
					images.value.push(results[i]['data']['fullurl'])
				}
				uni.hideLoading()

				uni.showToast({
					title: `成功上传${results.length}张图片`,
					icon: 'success'
				})
			})
			.catch(err => {
				uni.hideLoading()
			})
	}
</script>
<style lang="scss">
	.xuanxiang {
		width: 100%;
		display: flex;
		align-items: center;
		margin-top: 30rpx;
		overflow: hidden;
		justify-content: space-between;
		margin-bottom: 30rpx;

		.tt {
			font-size: 32rpx;
		}
	}

	.item {
		line-height: 100rpx;
		text-align: center;
	}

	.picker-view {
		width: 100%;
		height: 600rpx;
		margin-top: 20rpx;
		background: #FFFFFF;
		border-radius: 20rpx 20rpx 0 0;
	}

	.fixed {
		width: 100%;
		height: 194rpx;
		background: #FFFFFF;
		box-shadow: 0rpx -6rpx 14rpx 0rpx rgba(0, 0, 0, 0.03);
		border-radius: 0rpx 0rpx 0rpx 0rpx;
		position: fixed;
		bottom: 0%;

		.btn {
			width: 686rpx;
			height: 82rpx;
			background: #2AB4F5;
			border-radius: 12rpx 12rpx 12rpx 12rpx;
			text-align: center;
			line-height: 82rpx;
			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			font-size: 32rpx;
			color: #FFFFFF;
			margin: auto;
			margin-top: 32rpx;
		}
	}

	page {
		background: #F7F8FA;
	}

	.addjiancha {
		width: 100%;
		overflow: hidden;

		.addjianchaback {
			width: 100%;
			height: 450rpx;
			background: linear-gradient(180deg, #CAEEFF 71%, rgba(240, 250, 255, 0) 100%);
			border-radius: 0rpx 0rpx 0rpx 0rpx;
			position: absolute;
			z-index: -1;
		}

		.jianchaxm {
			width: 686rpx;
			margin: auto;
			overflow: hidden;
			margin-top: 32rpx;

			.cardform {
				width: 100%;
				background: #FFFFFF;
				box-shadow: 0rpx 4rpx 10rpx 0rpx rgba(0, 0, 0, 0.03);
				border-radius: 24rpx 24rpx 24rpx 24rpx;
				overflow: hidden;
				padding: 8rpx 0;

				.center {
					width: 630rpx;
					overflow: hidden;
					margin: auto;

					.lineform {
						width: 100%;
						min-height: 88rpx;
						display: flex;
						align-items: center;
						justify-content: space-between;
						border-bottom: 2rpx solid #F2F3F5;

						.lefttext {
							font-family: PingFang SC, PingFang SC;
							font-weight: 400;
							font-size: 28rpx;
							color: #1D2129;
						}

						.textsform {
							width: 630rpx;
							border-radius: 16rpx 16rpx 16rpx 16rpx;
							height: 130rpx;
							background: #F7F8FA;
							overflow: hidden;
							margin-top: 24rpx;
							margin-bottom: 32rpx;
							padding: 24rpx;

							.text1 {
								font-size: 24rpx;
								height: 80rpx;
							}
						}

						.images {
							width: 100%;
							display: flex;
							align-items: center;
							flex-wrap: wrap;
							margin-top: 24rpx;

							.image {
								width: 224rpx;
								height: 174rpx;
								border-radius: 16rpx 16rpx 16rpx 16rpx;
								position: relative;
								margin-right: 30rpx;
								margin-bottom: 10rpx;

								image {
									width: 224rpx;
									height: 174rpx;
									border-radius: 16rpx 16rpx 16rpx 16rpx;
									overflow: hidden;
								}

								.remivon {
									position: absolute;
									width: 30rpx;
									height: 30rpx;
									top: -6%;
									right: -6%;
									z-index: 9999;
								}
							}

							.imageadd {
								width: 224rpx;
								height: 174rpx;
								margin-right: 30rpx;
								margin-bottom: 10rpx;
								border-radius: 16rpx 16rpx 16rpx 16rpx;
							}

						}

						.msgtext {
							font-family: PingFang SC, PingFang SC;
							font-weight: 400;
							font-size: 24rpx;
							color: #86909C;
							margin-top: 16rpx;
							margin-bottom: 24rpx;
						}

						.rightcontent {
							display: flex;
							align-items: center;

							.righticon {
								width: 32rpx;
								height: 30rpx;
								margin-right: 4rpx;
							}

							input {
								text-align: right;
								font-size: 28rpx;
							}
						}
					}
				}
			}
		}
	}
</style>